package com.sfl.api_backend.controller.train;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sfl.api_backend.constant.HttpCode;
import com.sfl.api_backend.entity.*;
import com.sfl.api_backend.service.ITrainService;
import com.sfl.api_backend.utils.Api.RestResult;
import com.sfl.api_backend.utils.RandomID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/train")
@ResponseBody
@Slf4j
public class TrainController {
    @Resource
    private ITrainService trainService;


    @PostMapping("/list")
    @PreAuthorize("hasAuthority('User')")
    public RestResult list(@RequestBody Train train){
        try {
            log.info("list train: {}", train.getUserId());
            Wrapper<Train> Wrapper = new LambdaQueryWrapper<>();
            ((LambdaQueryWrapper<Train>) Wrapper).eq(Train::getUserId, train.getUserId());

            var result = trainService.list(Wrapper);
            return RestResult.success(result);
        }
        catch (RuntimeException e) {
            log.error("list train: {} error", train.getUserId());
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/make")
    @PreAuthorize("hasAuthority('User')")
    public RestResult make(@RequestBody Train train){
        try {
            log.info("make train: {}", train.getModelName());
            // set id
            train.setModelId(RandomID.getRandomID());
            train.setStatus(0);
            train.setProgress(0);
            // save
            trainService.save(train);
            return RestResult.success();
        }
        catch (RuntimeException e) {
            log.error("make train: {} error", train.getModelName());
            return RestResult.error(HttpCode.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('User')")
    public RestResult delete(@RequestBody Train train) throws Exception {
        try{
            log.info("delete train: {}", train.getModelId());
            trainService.removeById(train.getModelId());
            return RestResult.success();
        }
        catch (Exception e){
            log.info("delete train: {}", train.getModelId());
            return RestResult.error(HttpCode.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
}
